#!/bin/bash
# Install threadframe in an rvm environment. This involves patching Ruby
# 1.9.3

## Debugging 
# DEBUG='--trace' 
# VERBOSE=yes

## Error checking...
if [[ -z $rvm_path ]] ; then
    echo 'Variable $rvm_path seems not to be set. Is rvm in use? Aborting.' 1>&2
    exit 2
fi
# if [[ ! -d $rvm_path/repos ]] ; then
#     echo '$rvm_path/repos does is not a directory. Is rvm in use? Aborting.' 1>&2
#     exit 3
# fi

if cmp /bin/sh /bin/dash 2>/dev/null >/dev/null; then
    echo 'Warning your /bin/sh is dash. Making Ruby might not work!' 1>&2
fi


## OK. Now get to work...
mkdir -p $rvm_path/src/
builtin cd $rvm_path/src

doit() {
    [[ -n $VERBOSE ]] && echo "-- Running $* ..."
    eval $* || {
	rc=$?
	echo "Failed (exit $rc) running:
	$*"
	exit $rc
    }
}

branch_sans_ruby=1.9.3-p374
rvm_name=${branch_sans_ruby}
rvm_name=${branch_sans_ruby}-ndebugger

typeset -a steps

# steps=(remove-tf git-tf remove-patched-ruby install-patched-ruby \
#        install-gem)
steps=(remove-tf git-tf remove-patched-ruby install-patched-ruby)

for ((i=0; i<${#steps[@]}; i++)) ; do
    step=${steps[i]}
    case $step in 
	remove-tf)
	    rm -fr ruby-19-debugger
	    ;;
	git-tf)
	    doit "git clone https://code.google.com/p/ruby-19-debugger"
	    doit "builtin cd ruby-19-debugger"
	    ;;
	remove-patched-ruby)
	    doit "rvm remove $rvm_name"
	    rvm_ruby_path="$rvm_path/repo/$ruby_branch"
	    if [ $rvm_ruby_path == "/repo" ]; then
	       echo "EGAD!  The variables \$rvm_path and \$ruby_branch aren't defined.  Cowardly refusing to run 'rm -fr $rvm_ruby_path'"
	     else
	       rm -fr $rvm_ruby_path  # Had problems with svn locked.
	    fi
	    ;;
	install-patched-ruby)
	    doit "rvm $DEBUG --verify-downloads 1 install ${rvm_name} --patch patches/ruby-1.9.3-combined.patch%1" 
	    ;;
	# install-gem)
	#     source ${rvm_path}/scripts/rvm
	## have also trie:d __rvm_use
	#     doit "rvm $DEBUG use $rvm_name"
	## Have also tried simple "gem install" and "rvm gemset". 
	#     doit "rvm gem install rb-threadframe"
	#     ;;
    esac
done
    
